const _ = require('lodash')
const path = require('path')
const dao = require(path.join(process.cwd(),"dao/Dao"))

// 获取商品分类
module.exports.getAllCategories = function (level, conditions, cb) {
    dao.list('CategoryModel', {cat_deleted: false}, (err, categories) => {
        if (err) cb(err)
        const keyCategories = _.keyBy(categories, 'cat_id')
        if (!level) level = 3

        result = getTreeResult(keyCategories, categories, level)

        if (conditions) {
            total = result.length
            // pageNum = parseInt(conditions.pageNum)
            // pageSize = parseInt(conditions.pageSize)
            result = _.take(_.drop(result, pageNum * pageSize), pageSize)
            const resData = {}
            resData.total = total
            // resData.pageNum = pageNum
            // resData.pageSize = pageSize
            resData.result = result
            return cb(null, resData)
        }

        cb(null, result)
    })
}


/**  函数功能区 **/

// 获取树状分类
function getTreeResult (keyCategories, categories, level) {
    const result = []
    for (idx in categories) {
        const cat = categories[idx]
        // 被删除直接跳出循环不返回
        if(isDelete(keyCategories,cat)) continue
        if(cat.cat_pid == 0) {
            // 最顶级的父节点直接返回
            result.push(cat)
        } else {
            if (cat.cat_level >= level) continue
            // 通过父级cat_pid进行关联
            parantCat = keyCategories[cat.cat_pid]
            if (!parantCat) continue
            if(!parantCat.children) {
				parantCat["children"] = []
			}
			parantCat.children.push(cat)
        }
    }

    return addKeysDeep(result)
}
// 判断该分类是否被删除
function isDelete (keyCategories,cat) {
    if (cat.cat_pid == 0) {
        return cat.cat_deleted
    } else if (cat.cat_deleted) {
        return true
    } else {
        // cat_pid 是否关联父级
        parentCat = keyCategories[cat.cat_pid];
		if(!parentCat) return true;
		return isDelete(keyCategories,parentCat);
    }
}

function addKeysDeep (arr) {
    for (idx in arr) {
        const obj = arr[idx]
         obj.label = arr[idx].cat_name
         obj.value = arr[idx].cat_id
         obj.children = addKeysDeep(arr[idx].children) || []
    }
    return arr
}
